package org.threads.banktransactions;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.utils.Utils;

/**
 * Created by oler on 31.08.14.
 */
public class App {

    private static final Logger LOGGER = LoggerFactory.getLogger(App.class);

    private App() {
    }

    /**
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {

        final int n = 3;
        final int tasksCount = 100;
        final int minAmount = 1000;
        final int maxAmount = 10000;

        long amountBefore, amountAfter;

        Bank bank = new Bank();

        //Generating n accounts with random amounts
        for (int i = 0; i < n; i++) {
            Account acc = new Account((int) Utils.getRandom(minAmount, maxAmount));
            bank.addAccount(acc);
        }

        amountBefore = bank.calculateGeneralAmount();

        int acountsCount = bank.getAccounts().size();

        Thread[] threads = new Thread[tasksCount];
        for (int i = 0; i < tasksCount; i++) {

            int fromIndex = (int) Utils.getRandom(0, acountsCount - 1);
            int toIndex = fromIndex;
            while (fromIndex == toIndex) {
                toIndex = (int) Utils.getRandom(0, acountsCount - 1);
            }

            Thread t = new Thread(
                    new RemittanceTask(bank,
                            bank.getAccounts().get(fromIndex),
                            bank.getAccounts().get(toIndex),
                            (int) Utils.getRandom(10, minAmount / 2)
                    ));
            threads[i] = t;
            t.start();
        }

        for (int i = 0; i < tasksCount; i++) {
            threads[i].join();
        }

        amountAfter = bank.calculateGeneralAmount();

        LOGGER.info("Amount BEFORE transactions: " + amountBefore);
        LOGGER.info("Amount AFTER transactions:  " + amountAfter);
        if (amountAfter == amountBefore) {
            LOGGER.info("RESULT:  All correct!");
        } else {
            LOGGER.error("RESULT:  Mismatch!");
        }
    }
}
